// background.js
let blinkTimer = null;
let isBlinking = false;
let blinkFrameIndex = 0;
const iconSizes = [16, 32, 48, 64, 128, 256];
const blinkFrameCount = 12;

// 生成 normalIcons
const normalIcons = Object.fromEntries(iconSizes.map(size => [size, `icon/icon${size}.png`]));
// 生成多帧 blinkIcons
const blinkIconsFrames = Array.from({length: blinkFrameCount}, (_, i) =>
  Object.fromEntries(iconSizes.map(size => [size, `icon/icon${size}_blink${i}.png`]))
);

function setIcon(icons) {
  try {
    chrome.action.setIcon({ path: icons }, () => {
      if (chrome.runtime.lastError) {
        console.error('setIcon error:', chrome.runtime.lastError);
        stopBlink(); // 出错时自动停止
      }
    });
  } catch (e) {
    console.error('setIcon exception:', e);
    stopBlink();
}
}

function startBlink() {
  stopBlink(); // 先停止，防止重复启动
  isBlinking = true;
  blinkFrameIndex = 0;
  blinkTimer = setInterval(() => {
    setIcon(blinkIconsFrames[blinkFrameIndex]);
    blinkFrameIndex = (blinkFrameIndex + 1) % blinkFrameCount;
  }, 80); // 80ms一帧，约1秒一周期
}

function stopBlink() {
  if (blinkTimer) clearInterval(blinkTimer);
  blinkTimer = null;
  isBlinking = false;
  setIcon(normalIcons);
}

// 监听扩展事件
if (chrome.runtime.onSuspend) chrome.runtime.onSuspend.addListener(stopBlink);
if (chrome.runtime.onStartup) chrome.runtime.onStartup.addListener(stopBlink);
if (chrome.runtime.onDisable) chrome.runtime.onDisable.addListener(stopBlink);

// 定期检查状态
setInterval(() => {
  if (isBlinking && !blinkTimer) {
    console.warn('Blink state异常，自动恢复');
    stopBlink();
}
}, 5000);

// 监听前台消息
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg && msg.type === 'timerBlink') {
    if (msg.blink) {
      startBlink();
    } else {
      stopBlink();
    }
  }
}); 